<template>
  <div class="about">
    <a-card :bordered="false" style="max-width: 680px; margin: 24px auto">
      <template #title>个人中心</template>

      <a-skeleton v-if="loading" />

      <a-descriptions
        v-else
        :column="1"
        bordered
        size="large"
        :label-style="{ width: '120px' }"
      >
        <!-- 头像 -->
        <a-descriptions-item label="头像">
          <div style="display: flex; align-items: center;">
            <a-avatar
              :key="isEditing ? edited.userAvatar : user.userAvatar"
              :src="isEditing ? edited.userAvatar : user.userAvatar"
              :image-url="isEditing ? edited.userAvatar : user.userAvatar"
              size="large"
            />
            <template v-if="isEditing">
              <a-upload
                action="http://106.54.212.16:8101/api/file/upload"
                :with-credentials="true"
                :data="{ biz: 'user_avatar' }"
                accept="image/*"
                :show-upload-list="false"
                @success="handleUploadSuccess"
                @error="onUploadError"
              >
                <a-button type="outline" size="small" style="margin-left: 12px">
                  上传头像
                </a-button>
              </a-upload>
            </template>
          </div>
          <div
            v-if="isEditing && edited.userAvatar"
            style="margin-top: 8px; font-size: 12px; color: #888;"
          >
            新头像链接：{{ edited.userAvatar }}
          </div>
        </a-descriptions-item>

        <!-- 用户 ID（只读） -->
        <a-descriptions-item label="用户 ID">
          {{ user.id }}
        </a-descriptions-item>

        <!-- 用户名 -->
        <a-descriptions-item label="用户名">
          <div v-if="!isEditing">{{ user.userName ?? '—' }}</div>
          <a-input
            v-else
            v-model="edited.userName"
            placeholder="请输入用户名"
            style="width: 200px;"
          />
        </a-descriptions-item>

        <!-- 个人简介 -->
        <a-descriptions-item label="个人简介">
          <div v-if="!isEditing">{{ user.userProfile ?? '暂无' }}</div>
          <a-textarea
            v-else
            v-model="edited.userProfile"
            rows="3"
            placeholder="请输入个人简介"
          />
        </a-descriptions-item>

        <!-- 角色 -->
        <a-descriptions-item label="角色">
          <div v-if="!isEditing">
            <a-tag color="arcoblue">{{ user.userRole }}</a-tag>
          </div>
          <a-select
            v-else
            v-model="edited.userRole"
            :options="roleOptions"
            style="width: 200px;"
          />
        </a-descriptions-item>

        <!-- 注册时间 & 最近更新（只读） -->
        <a-descriptions-item label="注册时间">
          {{ formatDate(user.createTime) }}
        </a-descriptions-item>
        <a-descriptions-item label="最近更新">
          {{ formatDate(user.updateTime) }}
        </a-descriptions-item>
      </a-descriptions>

      <!-- 修改 & 提交 按钮 -->
      <div class="footer-buttons" style="text-align: right; margin-top: 16px;">
        <a-space>
          <a-button type="primary" :disabled="!isEditing" @click="onSubmit">提交</a-button>
          <a-button @click="toggleEdit">{{ isEditing ? '取消' : '修改' }}</a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { getLoginUserUsingGet, updateUserUsingPost } from '@/api/userController';

const router = useRouter();
const loading = ref(true);
const isEditing = ref(false);

// 原始用户数据
const user = reactive<any>({ /* ... */ });
// 编辑时的临时值
const edited = reactive({ userAvatar: '', userName: '', userProfile: '', userRole: '' });
// 角色选项
const roleOptions = [ { label: '管理员', value: 'admin' }, { label: '普通用户', value: 'user' } ];

function formatDate(dateStr?: string) {
  return dateStr ? dayjs(dateStr).format('YYYY-MM-DD HH:mm') : '—';
}

function toggleEdit() {
  if (isEditing.value) {
    Object.assign(edited, {
      userAvatar: user.userAvatar,
      userName: user.userName,
      userProfile: user.userProfile,
      userRole: user.userRole
    });
  }
  isEditing.value = !isEditing.value;
}

// 上传成功回调
// function onUploadSuccess(res: any) {
//   if (res.code === 0) {
//     edited.userAvatar = res.data;
//   } else {
//     console.error('上传失败：', res.message);
//   }
// }
function handleUploadSuccess(file: any) {
  const res = file.response as { code: number; data: string; message: string };
  if (res.code === 0) {
    // 拿到真正的 URL
    edited.userAvatar = res.data;
    // 同步到主显示
    // user.userAvatar = res.data;
  } else {
    console.error('上传失败：', res.message);
  }
}
function onUploadSuccess(response: any, file: any) {
  // response 是 { code: 0, data: 'https://...', message: 'ok' }
  if (response.code === 0) {
    const url = response.data;
    // 1. 更新编辑态用的值
    edited.userAvatar = url;
    // 2. 同步更新展示用的 user.userAvatar
    user.userAvatar = url;
  } else {
    console.error('上传失败：', response.message);
  }
}
function onUploadError(err: Error) {
  console.error('上传出错：', err);
}

// 提交修改
async function onSubmit() {
  const payload: any = { id: user.id };
  payload.userAvatar = edited.userAvatar;
  payload.userName = edited.userName;
  payload.userProfile = edited.userProfile;
  payload.userRole = edited.userRole;

  const res = await updateUserUsingPost(payload);
  if (res.data.code === 0) {
    Object.assign(user, payload);
    user.updateTime = new Date().toISOString();
    isEditing.value = false;
  } else {
    console.error('更新失败：', res.data.message);
  }
}

onMounted(async () => {
  try {
    const res = await getLoginUserUsingGet();
    if (res.data.code === 0 && res.data.data) {
      Object.assign(user, res.data.data);
      Object.assign(edited, {
        userAvatar: user.userAvatar,
        userName: user.userName,
        userProfile: user.userProfile,
        userRole: user.userRole,
      });
    } else {
      router.push('/user/login');
    }
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.footer-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>